<template>
  <div class="json-editor">
    <textarea ref="textarea" />
  </div>
</template>

<script>
import CodeMirror from "codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/lint/lint";
import "codemirror/addon/lint/lint.css";
import "codemirror/addon/lint/json-lint";
import "codemirror/addon/lint/javascript-lint";
import "codemirror/mode/javascript/javascript.js";
import "codemirror/theme/base16-dark.css";
import "codemirror/addon/fold/foldgutter.css";
import "codemirror/addon/fold/foldcode";
import "codemirror/addon/fold/foldgutter";
import "codemirror/addon/fold/brace-fold";
import "codemirror/addon/fold/comment-fold";
import "codemirror/addon/fold/markdown-fold";
import "codemirror/addon/fold/xml-fold";
import "codemirror/addon/fold/indent-fold";
import "codemirror/addon/hint/show-hint.css";
import "codemirror/addon/hint/show-hint.js";
import "codemirror/addon/hint/javascript-hint";
import "codemirror/addon/hint/xml-hint";
import "codemirror/addon/hint/sql-hint";
import "codemirror/addon/hint/anyword-hint";
import "codemirror/addon/search/match-highlighter";
import "codemirror/addon/edit/matchbrackets";
import "codemirror/addon/edit/closebrackets";
import "codemirror/mode/css/css.js";
import "codemirror/mode/vue/vue.js";
import "codemirror/theme/monokai.css";
export default {
  props: ["value"],
  watch: {
    "$props.value": {
      handler(val) {
        this.$nextTick(() => {
          const editorValue = this.edtor.getValue();
          // console.log(val, "x");
          // this.edtor.setValue(val);
          if (val !== editorValue) {
            this.edtor.setValue(this.value);
          }
        });
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    console.log(this.$props.value, "一些值");
    this.edtor = CodeMirror.fromTextArea(this.$refs.textarea, {
      lineNumbers: true,
      // mode: "text/x-vue",
      mode: "text/html",
      gutters: ["CodeMirror-lint-markers"],
      theme: "monokai",
      lint: true,
      lineWrapping: true,
    });

    this.edtor.setValue(JSON.stringify(this.value, null, 2));
    this.edtor.on("change", (cm) => {
      this.$emit("changed", cm.getValue());
      this.$emit("input", cm.getValue());
    });
  },
  methods: {
    getValue() {
      return this.edtor.getValue();
    },
  },
};
</script>

<style lang="scss" scoped>
.json-editor {
  height: 100%;
  position: relative;
  overflow: auto;
  ::v-deep {
    .CodeMirror {
      height: auto;
      min-height: 300px;
    }

    .CodeMirror-scroll {
      min-height: 300px;
    }

    .cm-s-rubyblue span.cm-string {
      color: #f08047;
    }
  }
}
</style>
